let sha1 = require('sha1');
let Wechat = require('./wechat');
let getRawBody = require('raw-body');
let util = require('./util');
let weixin = require('../reply')

module.exports = function (opts) {
  let wechat = new Wechat(opts);
  return async function (ctx, next) {
    let token = opts.token;
    let signature  =ctx.query.signature;
    let nonce = ctx.query.nonce;
    let timestamp = ctx.query.timestamp;
    let echostr = ctx.query.echostr;
    let str = [token, timestamp, nonce].sort().join('');
    let sha =  sha1(str);
    if (ctx.method ==='GET') {

      if (sha === signature) {
        ctx.body = echostr + ''
      } else {
        ctx.body = 'wrong'
      }
    } else if (ctx.method === 'POST') {
      if (sha !== signature) {
        ctx.body = 'wrong'
        return false
      }
      let data = await getRawBody(ctx.req, {
        length: ctx.length,
        limitL: '1mb',
        encoding: ctx.charset
      });
      let result = await util.xmlToJson(data);
      let replyBody = await weixin.reply.call(ctx,result);
      ctx.body = replyBody
    }
  }
};
